<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
<meta http-equiv="Cache-Control" content="no-siteapp" /> 
        <link href="/assets/css/bootstrap.min.css" rel="stylesheet" />
        <link rel="stylesheet" href="/css/style.css"/>
        <link rel="stylesheet" href="/assets/css/ace.min.css" />
        <link rel="stylesheet" href="/assets/css/font-awesome.min.css" />
        <link rel="stylesheet" href="/Widget/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css">
        <link href="/Widget/icheck/icheck.css" rel="stylesheet" type="text/css" />
		<!--[if IE 7]>
		  <link rel="stylesheet" href="/assets/css/font-awesome-ie7.min.css" />
		<![endif]-->
        <!--[if lte IE 8]>
		  <link rel="stylesheet" href="/assets/css/ace-ie.min.css" />
		<![endif]-->
	    <script src="/js/jquery-1.9.1.min.js"></script>
        <script src="/assets/js/bootstrap.min.js"></script>
        <script src="/assets/js/typeahead-bs2.min.js"></script>
		<!-- page specific plugin scripts -->
		<script src="/assets/js/jquery.dataTables.min.js"></script>
		<script src="/assets/js/jquery.dataTables.bootstrap.js"></script>
        <script type="text/javascript" src="/js/H-ui.js"></script>
        <script type="text/javascript" src="/js/H-ui.admin.js"></script>
        <script src="/assets/layer/layer.js" type="text/javascript" ></script>
        <script src="/assets/laydate/laydate.js" type="text/javascript"></script>
        <script type="text/javascript" src="/Widget/zTree/js/jquery.ztree.all-3.5.min.js"></script>
        <script src="/js/lrtk.js" type="text/javascript" ></script>
        <style>
        	.mybtn{
        		display: block;
        		width: 185px;
        		height: 30px;
        	}
        </style>
<title>销售订单列表</title>
</head>
<body>
<!--存储当前角色信息的隐藏域-->
<input id="roleName" type="hidden" th:value="${roleName}">
<div class=" page-content clearfix">
    <!--多条件筛选栏-->
<div id="orders_style">
    <div class="border clearfix">
   <span class="l_f">
    <a id="btn_add" href="/salesOrder/toAdd" title="订单录入" class="btn btn-warning Order_form"><i class="icon-plus"></i>订单录入</a>
    <a id="btn_batchdel" href="javascript:void(0)" class="btn btn-danger" onclick="delBatch()"><i class="icon-trash"></i>批量取消</a>
    <a id="btn_managed" onclick="getByKeeper()" href="javascript:void(0)" class="btn btn-primary"><i class="icon-eye-open"></i>可操作订单</a>
       <!--<a id="btn_unfinished" href="javascript:void(0)" class="btn btn-success"><i class="icon-trash"></i>已出库</a>-->
   </span>
        <!--商品总计-->
        <span class="r_f">共：<b></b>条记录</span>
    </div>
    <!--产品列表展示-->
<!--    <div class="h_products_list clearfix" id="products_list">
        &lt;!&ndash;左边的分类树&ndash;&gt;
        <div id="scrollsidebar" class="left_Treeview">
        </div>
    </div>-->
    <div class="search_style">
        <form action="/salesOrder/getByCondition" id="search_form">
            <ul class="search_content clearfix">
                <li><label class="l_f">客户：</label><input name="customerName" type="text"  class="text_add" placeholder="输入客户名称"  style=" width:250px"/></li>
                <li><label class="l_f">销售员：</label><input name="salesmanName" type="text"  class="text_add" placeholder="输入销售员名称"  style=" width:250px"/></li>
                <li><label class="l_f">库管员：</label><input name="keeperName" type="text"  class="text_add" placeholder="输入库管员名称"  style=" width:250px"/></li>
            </ul>
            <br>
            <ul class="search_content clearfix">
                <li><label class="l_f">录入时间：</label><input class="inline laydate-icon" id="enterDateStart" name="enterDateStart" style=" margin-left:10px;"></li>
                <li><label class="l_f">至</label><input class="inline laydate-icon" id="enterDateEnd" name="enterDateEnd" style=" margin-left:10px;"></li>
                <li><label class="l_f">出库时间：</label><input class="inline laydate-icon" id="outDateStart" name="outDateStart" style=" margin-left:10px;"></li>
                <li><label class="l_f">至</label><input class="inline laydate-icon" id="outDateEnd" name="outDateEnd" style=" margin-left:10px;"></li>
            </ul>
            <br>
            <ul class="search_content clearfix">
                <li>
                    <label class="l_f">类型：</label><select name="state" id="state" style="width: 180px">
                    <option value="">请选择</option>
                    <option value="已出库" >已出库</option>
                    <option value="未出库" >未出库</option>
                </select>
                </li>
                <li style="width:90px;"><button type="button" class="btn_search" onclick="search()"><i class="icon-search"></i>查询</button></li>
            </ul>
        </form>
    </div>
    <hr>
    <div class="table_menu_list" id="testIframe">
        <table th:fragment="orderlist" class="table table-striped table-bordered table-hover" id="sample-table">
            <thead>
            <tr>
                <th width="50px"><label><input type="checkbox" class="ace"><span class="lbl"></span></label></th>
                <th>ID</th>
                <th>录入日期</th>
                <th>出库日期</th>
                <th>销售员</th>
                <th>库管员</th>
                <th>客户</th>
                <th>订单状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr th:each="order : ${salesorders}">
                <td width="25px"><label><input type="checkbox" class="ace" name="ids" th:value="${order.id}"><span class="lbl"></span></label></td>
                <td th:text="${order.id}"></td>
                <td th:text="${#dates.format(order.enterDate,'yyyy-MM-dd')}"></td>
                <td th:text="${#dates.format(order.outDate,'yyyy-MM-dd')}"></td>
                <td th:text="${order.salesMan != null?order.salesMan.name:''}"></td>
                <td th:text="${order.keeper!=null?order.keeper.name:''}"></td>
                <td th:text="${order.customer!=null?order.customer.name:''}"></td>
                <td th:text="${order.state}"></td>
                <td class="td-manage">
                    <a title="查看" onclick="showDetails(this)" href="javascript:;"  class="btn btn-xs btn-info" ><i class="icon-eye-open bigger-120"></i>查看</a>
                    <a title="出库" onclick="showOutProducts(this)" href="javascript:;"   class="btn btn-xs btn-success"><i class="icon-ok bigger-120"></i>出库</a>
                    <a title="修改" onclick="toUpdate(this)" href="javascript:;"  class="btn btn-xs btn-primary" ><i class="icon-edit bigger-120"></i>修改</a>
                    <a title="取消" onclick="delById(this)" href="javascript:;" class="btn btn-xs btn-warning" ><i class="icon-trash  bigger-120"></i>取消</a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
 </div>
</div>
<!--查看详情弹窗-->
<div id="detail_div" style="display: none">
    <div id="salesorder_div">
        <table class="table table-striped table-bordered table-hover">
            <tbody>
                <tr>
                    <td>订单编号</td>
                    <td id="salesorderID_td">xxx</td>
                    <td>客户</td>
                    <td id="customerName_td">xxx</td>
                    <td>订单状态</td>
                    <td id="salesorderState_td">xxx</td>
                </tr>
                <tr>
                    <td>录入日期</td>
                    <td colspan="2" id="enterDate_td">xxx</td>
                    <td>出库日期</td>
                    <td colspan="2" id="outDate_td">xxx</td>
                </tr>
                <tr>
                    <td>销售员</td>
                    <td colspan="2" id="salesmanName_td">xxx</td>
                    <td>库管员</td>
                    <td colspan="2" id="keeperName_td">xxx</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div id="products_div">
        <table class="table table-striped table-bordered table-hover" id="detail_products_table">
            <thead>
                <tr>
                    <th>商品编号</th>
                    <th>商品名</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>
<!--商品出库列表弹窗-->
<div id="out_products_div" style="display: none">
    <table class="table table-striped table-bordered table-hover" id="out_products_table">
        <thead>
        <tr>
            <th>商品编号</th>
            <th>商品名</th>
            <th>数量</th>
            <th>仓库</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<!--客户详情弹窗-->
<div id="customer_detail_div" style="display: none">
    <table class="table table-striped table-bordered table-hover">
        <tr>
            <td>客户名</td>
            <td id="c_name_td"></td>
        </tr>
        <tr>
            <td>地址</td>
            <td id="c_address_td"></td>
        </tr>
        <tr>
            <td>联系人</td>
            <td id="c_linkman_td"></td>
        </tr>
        <tr>
            <td>联系电话</td>
            <td id="c_phone_td"></td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td id="c_email_td"></td>
        </tr>
    </table>
</div>
<!--商品详情弹窗-->
<div id="product_detail_div" style="display: none">
    <table class="table table-striped table-bordered table-hover">
        <tr>
            <td>商品名</td>
            <td id="p_name_td"></td>
        </tr>
        <tr>
            <td>产地</td>
            <td id="p_address_td"></td>
        </tr>
        <tr>
            <td>售价</td>
            <td id="p_price_td"></td>
        </tr>
        <tr>
            <td>类型</td>
            <td id="p_type_td"></td>
        </tr>
    </table>
</div>
</body>
<script th:inline="none">
    laydate({
        elem: '#enterDateStart',
        event: 'focus'
    });
    laydate({
        elem: '#enterDateEnd',
        event: 'focus'
    });
    laydate({
        elem: '#outDateStart',
        event: 'focus'
    });
    laydate({
        elem: '#outDateEnd',
        event: 'focus'
    });

    $(function(){
        buttonInit();//根据当前管理员身份初始化按钮
        createTable();//生成表格
    })

/*多条件查询*/
    function search() {
        $.get("/salesOrder/getByCondition",$("#search_form").serialize(),function(data){
            //console.log(data);
            $(".table_menu_list").html(data);
            buttonInit();
            createTable();
        })
    }

/*查询当前库管员能操作的订单*/
function getByKeeper() {
    $.get("/salesOrder/getByKeeper",null,function(data){
        $(".table_menu_list").html(data);
        buttonInit();
        createTable();
    })
}
/*根据当前管理员身份初始化按钮*/
function buttonInit(){
    var roleName = $("#roleName").val();
    if(roleName=="销售员"||roleName=="超级管理员"){
        //donothing
        $("#btn_managed").hide();
    }else{
        $("#btn_add").hide();
        $("#btn_batchdel").hide();
    }
    $("#sample-table tbody tr").each(function(){
        if($(this).find("td").eq(7).text()=='已出库'){
            $(this).find("a[title!='查看']").hide();
        }else{
            if(roleName=="销售员"){
                $(this).find("a[title='出库']").hide();
            }else if(roleName=="库管员"){
                $(this).find("a[title='修改']").hide();
                $(this).find("a[title='取消']").hide();
            }else if(roleName=="超级管理员"){
                $(this).find("a[title='出库']").hide();
            }else{
                $(this).find("a[title!='查看']").hide();
            }
        }
    })
}

/*商品出库*/
function showOutProducts(obj){
    //alert("出库");
    var oid = $(obj).parents("tr").find("td").eq(1).text();
    //alert("oid:"+oid);
    //获取当前库管员所能出库的商品
    $.getJSON("/salesOrder/getOutProducts","oid="+oid,function(data){
        console.log(data);
        //alert("length:"+data.length);
        if(data.length==0){
            layer.msg('对不起，该订单中没有您管理仓库中的商品！', {
                icon: 0,
                time: 1500 //2秒关闭（如果不配置，默认是3秒）
            });
        }else{
            $("#out_products_table tbody").html('');
            $.each(data,function(index,obj){
                $("#out_products_table tbody").append('<tr><td>'
                    +obj.pid+'</td><td>'
                    +obj.pname+'</td><td>'
                    +obj.pamount+'</td><td>'
                    +obj.wname+'<span hidden="hidden">'+obj.wid+'</span></td><td>'
                    +obj.pstate+'</td></td>'+
                    '<td><a title="出库" onclick="outWarehouse(this,'+oid+')" href="javascript:;"   class="btn btn-xs btn-success"><i class="icon-ok bigger-120"></i>出库</a></td></tr>')
            })
            layer.open({
                type: 1,
                title: '出库列表',
                area: ['700px', '300px'],
                shadeClose: true,
                content: $('#out_products_div'),
                btn: ['确认'],
                yes: function (index, layero) {
                    window.location.reload();
                    //layer.close(index);
                }
            })
        }
    })
}

function outWarehouse(obj,oid){
    var pid = $(obj).parents("tr").find("td").eq(0).text();
    var amount = $(obj).parents("tr").find("td").eq(2).text();
    var wid = $(obj).parents("tr").find("span").text();
    var data="pid="+pid+"&oid="+oid+"&wid="+wid+"&amount="+amount ;
        $.get("/salesOrder/outWarehouse",data,function(result){
           if(result==1){
               $(obj).parents("tr").remove()
               if ($("#out_products_table tbody tr").size()==0){
                   $("#out_products_table tbody").append("<tr><td colspan='10'>没有可以操作的商品了！</td></tr>")
               }
               layer.msg('出库成功！', {
                   icon: 1,
                   time: 1500 //2秒关闭（如果不配置，默认是3秒）
               });
           }else if(result==2){
               $(obj).parents("tr").remove();
               $("#out_products_table tbody").append("<tr><td colspan='10'>没有可以操作的商品了！</td></tr>")
               $("#sample-table").find("a[title='出库']").hide();
               layer.msg('出库成功！', {
                   icon: 1,
                   time: 1500 //2秒关闭（如果不配置，默认是3秒）
               });
           } else{
               layer.msg('出库失败，请联系系统管理员！', {
                   icon: 2,
                   time: 1500 //2秒关闭（如果不配置，默认是3秒）
               });
           }
        })
}

function delById(obj){
    var oid = $(obj).parents("tr").find("td").eq(1).text();
    layer.confirm('确认取消所选的记录吗？', function(index) {
        $.get("/salesOrder/delById","oid="+oid,function(data){
            if(data==0){
                layer.msg('取消失败，请联系系统管理员！', {
                    icon: 2,
                    time: 1500 //2秒关闭（如果不配置，默认是3秒）
                });
            }else{
                layer.msg('取消成功！', {
                    icon: 1,
                    time: 1500 //2秒关闭（如果不配置，默认是3秒）
                },function(){
                    window.location.reload();
                });
            }
        })
    })

}

function delBatch(){
    var objs = $("[name='ids']:checked");
    if(objs.length == 0) {
        layer.msg("请选择订单！", {
            icon: 0,
            time: 1000
        });
    } else {
        layer.confirm('确认取消所选的记录吗？', function(index) {
            var arr = [];
            $.each(objs, function(i, val) {
                arr.push(val.value);
            });
            var data = {
                ids: arr
            };
            $.ajax({
                url: '/salesOrder/delBatch',
                type: 'post',
                data: data,
                success: function(result, status, xhr) {
                    if(result==0){
                        layer.msg('取消失败，请联系系统管理员！', {
                            icon: 2,
                            time: 1500 //2秒关闭（如果不配置，默认是3秒）
                        });
                    }else{
                        layer.msg('取消成功！', {
                            icon: 1,
                            time: 1500 //2秒关闭（如果不配置，默认是3秒）
                        },function(){
                            window.location.reload();
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.info('出错了！');
                }
            });
        });
    }
}

/*跳转到修改页面*/
function toUpdate(obj) {
    var oid = $(obj).parents("tr").find("td").eq(1).text();
    $.get("/salesOrder/isBegined","oid="+oid,function(data){
        if(data==0){
            window.location.href="/salesOrder/toUpdate?oid="+oid;
        }else {
            layer.msg('该订单已开始，无法进行修改！', {
                icon: 0,
                time: 1500 //2秒关闭（如果不配置，默认是3秒）
            });
        }
    })

}

/*显示订单中对的用户详细*/
function showCustomer(customer){
    $("#c_name_td").text(customer.name);
    $("#c_address_td").text(customer.address);
    $("#c_linkman_td").text(customer.linkman);
    $("#c_phone_td").text(customer.phone);
    $("#c_email_td").text(customer.email);
    layer.open({
        type: 1,
        title: '客户信息',
        area: ['500px', '300px'],
        shadeClose: true,
        content: $('#customer_detail_div'),
        btn: ['确定'],
        yes: function (index, layero) {
            layer.close(index);
        }
    })
}

/*显示订单中的商品详细*/
function showProductDetail(pro){
    $("#p_name_td").text(pro.pname);
    $("#p_address_td").text(pro.paddress);
    $("#p_price_td").text(pro.psalesprice+pro.punit);
    $("#p_type_td").text(pro.ptname);
    layer.open({
        type: 1,
        title: '商品信息',
        area: ['500px', '300px'],
        shadeClose: true,
        content: $('#product_detail_div'),
        btn: ['确定'],
        yes: function (index, layero) {
            layer.close(index);
        }
    })
}

/*查看详情*/
function showDetails(obj){
    //订单id
    var oid = $(obj).parents("tr").find("td").eq(1).text();
    //alert("订单id是:"+oid);
    $.getJSON("/salesOrder/getDetail","oid="+oid,function(data){
        console.log(data);
        //alert(data.salesOrder.id);
        var oid = data.salesOrder.id;
        var cname = data.salesOrder.customer!=null?data.salesOrder.customer.name:'';
        var state = data.salesOrder.state!=null?data.salesOrder.state:'';
        var enterDate = data.salesOrder.enterDate!=null?data.salesOrder.enterDate:'';
        var outDate = data.salesOrder.outDate!=null?data.salesOrder.outDate:'';
        var salesManName = data.salesOrder.salesMan!=null?data.salesOrder.salesMan.name:'';
        var keeperName = data.salesOrder.keeper!=null?data.salesOrder.keeper.name:'';
        $("#salesorderID_td").text(oid);
        $("#customerName_td").html('<a href="javascript:void(0);" onclick="showCustomer('+JSON.stringify(data.salesOrder.customer).replace(/\"/g,"'")+')">'+cname+'</a>');
        $("#salesorderState_td").text(state);
        $("#enterDate_td").text(enterDate);
        $("#outDate_td").text(outDate);
        $("#salesmanName_td").text(salesManName);
        $("#keeperName_td").text(keeperName);
        var total = 0;
        $("#detail_products_table tbody").html('');
        $.each(data.details,function(index,obj){
            $("#detail_products_table tbody").append('<tr><td>'
                +obj.pid+'</td><td><a href="javascript:void(0)" onclick="showProductDetail('+JSON.stringify(obj).replace(/\"/g,"'")+')">'
                +obj.pname+'</a></td><td>'
                +obj.psalesprice+obj.punit+'</td><td>'
                +obj.pamount+'</td><td>'
                +accMul(Number.parseFloat(obj.psalesprice),Number.parseFloat(obj.pamount))+'元</td><td>'
                +obj.pstate+'</td></td></tr>')
            total = total+accMul(Number.parseFloat(obj.psalesprice),Number.parseFloat(obj.pamount));
        })
        $("#detail_products_table tbody").append("<tr><td>总计</td><td colspan='100'>"+total+"元</td></tr>");
        layer.open({
            type: 1,
            title: '订单详情',
            area: ['700px', '400px'],
            shadeClose: true,
            content: $('#detail_div'),
            btn: ['确认','取消'],
            yes: function (index, layero) {
                layer.close(index);
            }
        })
    })
}

function createTable(){
			// $.getJSON(url,param,function(data){
			 var len = $("#sample-table tbody tr").size();
			/*总记录数*/
			 $(".r_f b").html(len);
			var oTable1 = $('#sample-table').dataTable( {
			"lengthMenu":[5,10, 25, 50],
			"aaSorting": [[ 1, 'asc' ]],//默认第几个排序
			"bStateSave": true,//状态保存
			"bAutoWidth": false,
			"aoColumnDefs": [
			  //{"bVisible": false, "aTargets": [ 3 ]} //控制列的隐藏显示
			  {"orderable":false,"aTargets":[0,4,5,6,7,8]}// 制定列不参与排序
			],
		} );

			/*全选功能*/
			$('table th input:checkbox').on('click' , function(){
				var that = this;
				$(this).closest('table').find('tr > td:first-child input:checkbox')
				.each(function(){
					this.checked = that.checked;
					$(this).closest('tr').toggleClass('selected');
				});
					
			});
		
		
			$('[data-rel="tooltip"]').tooltip({placement: tooltip_placement});
			function tooltip_placement(context, source) {
				var $source = $(source);
				var $parent = $source.closest('table');
				var off1 = $parent.offset();
				var w1 = $parent.width();
		
				var off2 = $source.offset();
				var w2 = $source.width();
		
				if( parseInt(off2.left) < parseInt(off1.left) + parseInt(w1 / 2) ) return 'right';
				return 'left';
			}
}

//解决js浮点数乘法不精确的bug
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    }
    catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    }
    catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

$(function() {
	$("#products_style").fix({
		float : 'left',
		//minStatue : true,
		skin : 'green',	
		durationTime :false,
		spacingw:30,//设置隐藏时的距离
	    spacingh:260,//设置显示时间距
	});
});

//初始化宽度、高度  
 $(".widget-box").height($(window).height()-80);
$(".table_menu_list").width($(window).width());
//$("#sample-table").width($(window).width()-230);
//alert($(window).width())
 $(".table_menu_list").height($(window).height()-80);
  //当文档窗口发生改变时 触发  
    $(window).resize(function(){
	$(".widget-box").height($(window).height()-80);
	 $(".table_menu_list").width($(window).width());
	  $(".table_menu_list").height($(window).height()-80);
	})

//面包屑返回值
var index = parent.layer.getFrameIndex(window.name);
parent.layer.iframeAuto(index);
$('.Order_form').on('click', function(){
	var cname = $(this).attr("title");
	var chref = $(this).attr("href");
	var cnames = parent.$('.Current_page').html();
	var herf = parent.$("#iframe").attr("src");
    parent.$('#parentIframe').html(cname);
    parent.$('#iframe').attr("src",chref).ready();
	parent.$('#parentIframe').css("display","inline-block");
	parent.$('.Current_page').attr({"name":herf,"href":"javascript:void(0)"}).css({"color":"#4c8fbd","cursor":"pointer"});
    parent.layer.close(index);
	
});
</script>
</html>
